<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home/welcome">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCate">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 树形表格区域 -->
      <tree-table
        ref="table"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是否启用的插槽 -->
        <template #isok="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted==false" style="color:lightgreen"></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <!-- 排序的插槽 -->
        <template #order="scope">
          <el-tag type="primary" size="normal" effect="dark" v-if="scope.row.cat_level==0">一级</el-tag>
          <el-tag type="success" size="normal" effect="dark" v-if="scope.row.cat_level==1">二级</el-tag>
          <el-tag type="warning" size="normal" effect="dark" v-if="scope.row.cat_level==2">三级</el-tag>
        </template>
        <!-- 操作的插槽 -->
        <template #opt="scope">
          <el-button type="primary" icon="el-icon-edit" size="small" @click="editCate(scope.row)">编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete-solid"
            size="small"
            @click="deleteCate(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[3,5,10,15]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加分类的对话框 -->
      <el-dialog title="添加分类" :visible.sync="cateflag" width="50%" @close="resetForm">
        <el-form
          :model="addCateForm"
          :rules="cateRules"
          ref="addCateForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称:" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类:" class="textLeft">
            <!-- 两层分类数据的展示 -->
            <el-cascader
              size="medium"
              v-model="selectCate"
              :options="parentCateList"
              :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children'}"
              @change="parentChange"
              clearable
              change-on-select
              filterable
              ref="parentCateList"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cateflag = false">取 消</el-button>
          <el-button type="primary" @click="saveCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑分类的对话框 -->
      <el-dialog title="编辑分类" :visible.sync="editCateflag" width="50%" @close="resetForm">
        <el-form
          :model="addCateForm"
          :rules="cateRules"
          ref="addCateForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称:" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCateflag = false">取 消</el-button>
          <el-button type="primary" @click="saveEditCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 接收前两层分类的信息
      parentCateList: "",
      // 添加分类中选择的信息
      selectCate: [],
      // 接收分类信息
      cateList: [],
      // 添加分类是否显示
      cateflag: false,
      //发送请求列表信息
      queryinfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 表单收集添加分类的信息
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0
      },
      // 当前选中的cata
      curEditCate: "",
      // 总数据条数
      total: 0,
      // 对树形表信息的配置
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok"
        },
        {
          label: "排序",
          type: "template",
          template: "order"
        },
        {
          label: "操作",
          type: "template",
          template: "opt"
        },
      ],
      // 对添加分类进行验证的规则
      cateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ]
      },
      // 级联选择器中的配置项
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: "hover"
      },
      // 显示编辑框
      editCateflag: false
    }
  },
  // 开始获取分类列表的信息
  created () {
    this.getCategories();
  },
  methods: {
    // 获取分类列表
    async getCategories () {
      const res = await this.axios.get("categories", { params: this.queryinfo })
      if (res.meta.status != 200)
        return this.$message.error({
          message: "获取商品分类失败",
          duration: 1000
        })
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    // 处理分页中单页数目出现变化的情况 立即更新数据
    handleSizeChange (newsize) {
      this.queryinfo.pagesize = newsize;
      this.getCategories();
    },
    // 当分页中分页页数出现变化 立即更新数据
    handleCurrentChange (newpage) {
      this.queryinfo.pagenum = newpage;
      this.getCategories();
    },
    // 添加分类的函数
    addCate () {
      // 获取两层分类的数据
      this.getParentCateList();
    },
    // 获取父级分类的数据列表
    async getParentCateList () {
      // 因为分类只需要获取前两层 所以为2
      let res = await this.axios.get("categories", { params: { type: 2 } });
      if (res.meta.status != 200)
        return this.$message.error(
          {
            message: "获取两层分类数据失败",
            duration: 1000
          }
        )
      // 获取成功后 给parentcCateList赋值
      this.parentCateList = res.data;
      this.cateflag = true;
      console.log(this.parentCateList);
    },
    // 当选择项变化后
    parentChange () {
      console.log(this.selectCate);
      // 选中后下拉框消失
      this.$refs.parentCateList.dropDownVisible = false;
      if (this.selectCate.length > 0) {
        // 取最后一个分类的id
        this.addCateForm.cat_pid = this.selectCate[this.selectCate.length - 1];
        this.addCateForm.cat_level = this.selectCate.length;
      }
      else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0
      }
    },
    // 保存新商品分类到后台
    saveCate () {
      console.log(2);
      this.$refs.addCateForm.validate(async valid => {
        console.log(valid);

        if (!valid) return;
        console.log(2);

        let res = await this.axios.post("categories", this.addCateForm);
        if (res.meta.status != 201)
          return this.$message.error({
            message: "添加分类失败",
            duration: 1000
          });
        this.$message.success({
          message: "添加分类成功",
          duration: 1000
        })
        this.getCategories();
        console.log(this.addCateForm);
        console.log(this.cateList);

        this.cateflag = false
      })
      // 重新更新数据

    },
    // 删除分类
    deleteCate (id) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 发送请求去删除数据
          this.axios.delete("categories/" + id).then(res => {
            if (res.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              // 重新获取数据
              this.getCategories();
            } else {
              this.$message.error({
                message: "删除失败",
                duration: 1000
              });
            }
          });
        })
        .catch(() => { });
    },
    // 编辑分类 其实只能编辑分类名字
    editCate (row) {
      this.editCateflag = true;
      this.addCateForm.cat_name = row.cat_name;
      this.addCateForm.cat_pid = row.cat_id;
      console.log(this.addCateForm);

    },
    // 保存编辑分类
    saveEditCate () {
      this.$refs.addCateForm.validate(async valid => {
        if (!valid) return;
        let res = await this.axios.put("categories/" + this.addCateForm.cat_pid, { cat_name: this.addCateForm.cat_name });
        if (res.meta.status != 200)
          return this.$message.error({
            message: "编辑分类失败",
            duration: 1000
          });
        this.$message.success({
          message: "编辑分类成功",
          duration: 1000
        })
        this.editCateflag = false;
        this.getCategories();
        this.addCateForm.cat_name = "";
        this.addCateForm.cat_pid = 0;
        console.log(this.addCateForm);
        console.log(this.cateList);
      })
    },
    // 重置表单中内容
    resetForm () {
      this.$refs.addCateForm.resetFields();
      // 清空数组的同时清空 选择的数据
      this.selectCate = []
      // 清空之前改变的表单数据
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_name = "";
    },
  },
}
</script>

<style  scoped>
.el-col-24 {
  width: 0%;
  margin-bottom: 20px;
}
.textLeft {
  text-align: left !important;
}
</style>